<?php
/**
 * Created by PhpStorm.
 * User: cy
 * Date: 18-12-31
 * Time: 下午4:57
 */

namespace app\admin_module\controllers;


use app\common\Helpers;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

class CommonController extends \yii\web\Controller
{

    protected $actions=['*'];//需要用规则去验证的方法
    protected $except=[];//不需要规则去验证的方法
    protected $mustLogin=['*'];//必须要登录的方法
    protected $noLogin=[];
    /**
     * 这个装饰器方法可以抽离到公共控制器中，提高重用性
     */
    public function behaviors()
    {
        $this->noLogin || $this->noLogin=$this->getNoLoginMethod();

        return [
            'access' => [
                'class' => AccessControl::class,
                'user'=>'admin',//默认为'user'=>'user',和配置文件中的用户认证组件对应
                'only' => $this->actions,
                'except'=>$this->except,
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => $this->mustLogin,
                        'roles' => ['@'],
                    ],
                    [
                        'allow' => true,
                        'actions' => $this->noLogin,
                        'roles' => ['?'],
                    ],

                ],
            ],
            //控制方法的请求方式
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'logout' => ['get'],
                ],
            ],
        ];
    }

    /**
     * 设置不需要登录的方法列表
     */
    protected function getNoLoginMethod()
    {
        if (in_array('*', $this->mustLogin)) {
            return [];
        }

        //利用反射获取可通过url访问的方法
        $methodList = array_map(function($method){
            if (strpos($method, 'action') === false || $method==='actions') return null;

            return Helpers::parseHumpToUrl($method);
        },get_class_methods($this));

        return array_diff(array_filter($methodList), $this->mustLogin);
    }

}